import { type FC } from 'react';
import { useMemoizedFn } from 'ahooks';
import { StatusBar } from 'expo-status-bar';
import { TouchableWithoutFeedback } from 'react-native';
import { useBackHandler } from '@react-native-community/hooks';
import Animated, { withTiming, useAnimatedStyle } from 'react-native-reanimated';
import { MaskProps } from './types';
import { easing } from './hooks';
import styles from './styles';

const Mask: FC<MaskProps> = (props) => {
  const {
    show,
    height,
    duration,
    maskClosable = true,
    statusBarStyle = 'light'
  } = props;

  const maskStyle = useAnimatedStyle(() => {
    const config = { duration, easing };
    const val = withTiming(show ? 1 : 0, config);
    return { height: height, opacity: val };
  });

  const handlePress = useMemoizedFn(() => {
    if (maskClosable) props.onClose?.();
  });

  const onAndroidBack = useMemoizedFn(() => {
    if (show) props.onClose?.();
    return show;
  });

  useBackHandler(onAndroidBack);

  return (
    <>
      {show && <StatusBar style={statusBarStyle} />}
      <TouchableWithoutFeedback onPress={handlePress}>
        <Animated.View style={[styles.mask, maskStyle]} />
      </TouchableWithoutFeedback>
    </>
  );
}

export default Mask;